<template>
  <px-card shadow="never">
    <px-form ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-position="right">
      <px-row :gutter="16">
        <px-col :span="5">
          <px-form-item label="字典名称" prop="typeCode">
            <px-select v-model="queryParams.typeCode" filterable placeholder="请输入字典名称进行搜索" clearable @change="handleChange">
              <px-option v-for="dict in dictNameList" :key="dict.typeCode" :label="dict.typeName" :value="dict.typeCode" />
            </px-select>
          </px-form-item>
        </px-col>
        <px-col :span="5">
          <px-form-item label="字典项名称" prop="itemName">
            <px-input v-model="queryParams.itemName" maxlength="50" placeholder="请输入字典项名称" clearable @keyup.enter="getList">
              <template #suffix>
                <px-icon style="cursor: pointer" @click="getList">
                  <search />
                </px-icon>
              </template>
            </px-input>
          </px-form-item>
        </px-col>
        <px-col :span="5">
          <px-form-item label="字典项编码" prop="itemValue">
            <px-input v-model="queryParams.itemValue" maxlength="50" placeholder="请输入字典项编码" clearable @keyup.enter="getList">
              <template #suffix>
                <px-icon style="cursor: pointer" @click="getList">
                  <search />
                </px-icon>
              </template>
            </px-input>
          </px-form-item>
        </px-col>
        <px-col :span="5">
          <px-form-item label="状态" prop="status">
            <px-select v-model="queryParams.status" placeholder="数据状态" filterable clearable>
              <px-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
            </px-select>
          </px-form-item>
        </px-col>
        <px-col :span="4">
          <px-button type="primary" @click="getList">查询</px-button>
          <px-button @click="resetQuery">重置</px-button>
        </px-col>
      </px-row>
    </px-form>

    <div style="display: flex; justify-content: space-between">
      <px-row :gutter="10" class="mb8">
        <px-col :span="1.5">
          <px-button v-has="'DICT_DATA_ITEM_ADD'" type="primary" @click="handleAdd">新增</px-button>
        </px-col>
        <px-col :span="1.5">
          <px-button v-has="'DICT_DATA_ITEM_DOWNLOAD'" type="primary" plain @click="handleDownload">下载模板</px-button>
        </px-col>
        <px-col :span="1.5">
          <px-upload v-has="'DICT_DATA_ITEM_IMPORT'" action="#" :http-request="handleImport" :show-file-list="false" accept=".xlsx, xls">
            <px-button type="primary" plain>批量导入</px-button>
          </px-upload>
        </px-col>
      </px-row>
      <px-button type="primary" plain @click="backMainPage">返回</px-button>
    </div>

    <px-table
      v-loading="loading"
      :data="list"
      row-key="id"
      :header-cell-style="{ background: '#e7eefb', color: '#000' }"
      :tree-props="{ children: 'children', hasChildren: true }"
      border
    >
      <px-table-column show-overflow-tooltip label="字典项名称" prop="itemName" min-width="120" />
      <px-table-column label="字典项编码" show-overflow-tooltip min-width="120" prop="itemValue" />
      <px-table-column label="字典项描述" show-overflow-tooltip prop="itemDesc" min-width="160" />
      <px-table-column label="字典排序" width="80" prop="itemSort" />
      <px-table-column label="状态" width="80" prop="status">
        <template #default="scope">
          <span>{{ scope.row.status === "VALID" ? "启用" : "禁用" }}</span>
        </template>
      </px-table-column>
      <px-table-column label="创建时间" prop="createTime" width="180" />
      <px-table-column label="操作" width="180" class-name="small-padding fixed-width" align="center">
        <template #default="scope">
          <px-tooltip content="编辑" placement="top">
            <px-button
              v-has="'DICT_DATA_ITEM_EDIT'"
              link
              type="primary"
              :disabled="scope.row.status === 'INVALID'"
              icon="Edit"
              @click="handleUpdate(scope.row)"
            />
          </px-tooltip>
          <px-tooltip :content="scope.row.status === 'VALID' ? '禁用' : '启用'" placement="top">
            <px-button
              v-has="'DICT_DATA_ITEM_ABLE'"
              link
              :type="scope.row.status === 'VALID' ? 'warning' : 'success'"
              :icon="scope.row.status === 'VALID' ? 'CircleClose' : 'CircleCheck'"
              @click="handleEnable(scope.row)"
            />
          </px-tooltip>
          <px-tooltip content="添加子级" placement="top">
            <px-button
              v-has="'DICT_DATA_ITEM_ADD'"
              link
              type="primary"
              :disabled="scope.row.status === 'INVALID'"
              icon="plus"
              @click="handleAddChildren(scope.row)"
            />
          </px-tooltip>
          <px-tooltip content="删除" placement="top">
            <px-button v-has="'DICT_DATA_ITEM_DELETE'" link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
          </px-tooltip>
        </template>
      </px-table-column>
    </px-table>

    <!-- 添加或修改参数配置对话框 -->
    <px-dialog v-model="open" :title="title" width="800px" destroy-on-close append-to-body>
      <px-form ref="dataRef" :model="form" :rules="rules" label-width="120px">
        <px-form-item v-if="parentInfo.id" label="父级名称">
          <px-input :value="parentInfo.name" disabled />
        </px-form-item>
        <px-form-item label="字典项名称" prop="itemName">
          <px-input v-model="form.itemName" maxlength="50" clearable placeholder="请输入字典项名称" />
        </px-form-item>
        <px-form-item label="字典项编码" prop="itemValue">
          <px-input v-model="form.itemValue" maxlength="50" :disabled="form.id" clearable placeholder="请输入字典项编码" />
        </px-form-item>
        <px-form-item label="字典项描述" prop="itemDesc">
          <px-input
            v-model="form.itemDesc"
            type="textarea"
            maxlength="1000"
            clearable
            :autosize="{ minRows: 2, maxRows: 6 }"
            placeholder="请输入对字典项的相关描述"
          />
        </px-form-item>
        <px-form-item label="字典排序" prop="itemSort">
          <px-input-number v-model="form.itemSort" controls-position="right" :min="0" />
        </px-form-item>
      </px-form>
      <template #footer>
        <div class="dialog-footer">
          <px-button @click="cancel">取 消</px-button>
          <px-button type="primary" @click="submitForm">确 定</px-button>
        </div>
      </template>
    </px-dialog>
  </px-card>
</template>

<script setup lang="ts">
import { dataDel, dataEnable, dataImport, dataList, dataSave, dataUpdate, listType } from "@/api/system/dictData";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, onMounted, reactive, ref, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";

defineOptions({
  name: "SYSTEM_DATA_DICT_ITEM"
});

const { proxy }: any = getCurrentInstance();

const sys_normal_disable = ref([
  {
    label: "启用",
    value: "VALID"
  },
  {
    label: "禁用",
    value: "INVALID"
  }
]);

const open = ref(false);
const loading = ref(false);
const title = ref("");
const route = useRoute();
const router = useRouter();

const data = reactive<Record<string, any>>({
  form: {},
  parentInfo: {},
  queryParams: {
    itemValue: undefined,
    itemName: undefined,
    status: undefined,
    id: undefined,
    pageSize: 999
  },
  rules: {
    itemName: [{ required: true, message: "字典项名称不能为空", trigger: "blur" }],
    itemValue: [{ required: true, message: "字典项编码不能为空", trigger: "blur" }]
  },
  list: [], // 字典项数据列表
  dictNameList: [] // 父级字典名称的列表
});

const { queryParams, form, rules, parentInfo, list, dictNameList } = toRefs(data);

/** 查询父级字典类型列表获取字典名称 */
const getDictNameList = async () => {
  const res: any = await listType(queryParams.value);
  dictNameList.value = res?.data;
};

const handleChange = e => {
  queryParams.value.typeCode = e;
  getList();
};
/** 查询字典数据项列表 */
const getList = async () => {
  loading.value = true;
  const data = await dataList(queryParams.value);
  list.value = data || [];
  loading.value = false;
};

onMounted(() => {
  const queryCode = route.query.typeCode;
  getDictNameList();
  queryParams.value.typeCode = queryCode;
  getList();
});

/** 取消按钮 */
const cancel = () => {
  open.value = false;
  reset();
};
/** 表单重置 */
const reset = () => {
  form.value = {
    itemName: "",
    itemValue: "",
    itemDesc: "",
    itemSort: 0,
    status: "VALID"
  };
  parentInfo.value = {
    id: undefined,
    name: ""
  };
};
/** 重置按钮操作 */
const resetQuery = () => {
  proxy.resetForm("queryRef");
  queryParams.value.typeCode = route.query.typeCode;
  getList();
};
/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  open.value = true;
  title.value = "添加字典数据";
};
const handleImport = async (options: any) => {
  try {
    console.log("导入文件", options);
    const { file } = options;
    const formData = new FormData();
    formData.append("file", file);
    formData.append("typeId", queryParams.value.typeCode);
    await dataImport(formData);
    PxMessage.success("导入成功");
    getList();
  } catch (error) {
    console.log(error);
  }
};

const handleDownload = () => {
  proxy.download("post", "/account/api/v1/dictItem/downloadTemplate");
};
/** 修改按钮操作 */
const handleUpdate = row => {
  reset();
  open.value = true;
  title.value = "修改字典数据";
  form.value = JSON.parse(JSON.stringify(row));
};
/** 启用/禁用按钮操作 */
const handleEnable = row => {
  PxMessageBox.confirm(`是否确认${row.status === "VALID" ? "禁用" : "启用"}字典项名称为${row.itemName}的数据项？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await dataEnable({ ids: [row.id], status: row.status === "VALID" ? "INVALID" : "VALID" });
      PxMessage.success(`${row.status === "VALID" ? "禁用" : "启用"}成功`);
      getList();
    })
    .catch(() => {});
};
const handleAddChildren = (row: any) => {
  console.log(row);
  open.value = true;
  parentInfo.value.id = row.itemValue;
  parentInfo.value.name = row.itemName;
  title.value = "添加子级";
};
/** 提交按钮 */
const submitForm = () => {
  proxy.$refs["dataRef"].validate(valid => {
    if (valid) {
      if (form.value.id) {
        dataUpdate({
          typeId: queryParams.value.typeCode,
          parentId: parentInfo.value.id,
          ...form.value
        }).then(() => {
          open.value = false;
          reset();
          getList();
        });
      } else {
        dataSave({
          typeId: queryParams.value.typeCode,
          parentId: parentInfo.value.id,
          ...form.value
        }).then(() => {
          open.value = false;
          reset();
          getList();
        });
      }
    }
  });
};
/** 删除按钮操作 */
const handleDelete = row => {
  PxMessageBox.confirm(`是否确认删除字典项名称为${row.itemName}的数据项？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await dataDel({ ids: [row.id] });
      getList();
    })
    .catch(() => {});
};
//返回数据字典
const backMainPage = () => {
  router.push("/system/dataDict");
};
</script>
